package widget;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;

/**
 * Created by LLAP on 2017/12/14.
 * Copyright (c) 2017 LLAP. All rights reserved.
 */
public class TMultipleSelect extends TComponent {
    private LinkedList<JCheckBox> list;

    public TMultipleSelect(String name, Object[] options, String comment, boolean required) {
        super(
                name,
                new JPanel(new GridLayout(1, options.length, 5, 5)),
                comment,
                required
        );
        list = new LinkedList<>();
        for (Object i : options) {
            JCheckBox checkBox = new JCheckBox(i.toString());
            field.add(checkBox);
            list.add(checkBox);
        }
    }

    public TMultipleSelect(String name, Object[] options, String comment) {
        this(name, options, comment, false);
    }

    @Override
    public void clear() {
        for (JCheckBox i : list) {
            i.setSelected(false);
        }
    }

    public TMultipleSelect(String name, Object[] options) {
        this(name, options, name);
    }

    @Override
    public HashMap<String, Object> getData() throws IllegalArgumentException {
        HashMap<String, Object> ret = new HashMap<>();
        /*String selected = "";
        for (JCheckBox i : list) {
            if (i.isSelected()) {
                selected += i.getText() + ", ";
            }
        }
        if (selected.equals("")) ret.put(name, "");
        else ret.put(name, selected.substring(0, selected.length() - 2));
        return ret;*/
        ArrayList<String> selected = new ArrayList<>();
        boolean flag = false;
        for (JCheckBox i : list) {
            if (i.isSelected()) {
                flag = true;
                selected.add(i.getText());
            }
        }
        if (required && !flag) throw new IllegalArgumentException(comment + "需要选择至少一项");
        ret.put(name, selected);
        return ret;
    }
}
